# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
""" MindVison Classification infer script. """

import numpy as np

import mindspore
from mindspore import context
from mindspore.train import Model
from mindspore import Tensor
from mindspore.train.serialization import load_checkpoint, load_param_into_net

from mindvision.common import images as coimg
from mindvision.classification.utils import get_config, parse_args
from mindvision.classification.models.build_train import build_model
from mindvision.classification.utils import get_image_list, preprocess

def main(pargs):
    # set config context
    config = get_config(pargs.config, overrides=pargs.override)
    context.set_context(mode=context.GRAPH_MODE,
                        device_target=config.device_target)

    # set network, loss, optimizer
    network = build_model(config)

    # load pretrain model
    param_dict = load_checkpoint(config.pretrained_model)
    load_param_into_net(network, param_dict)

    # init the whole Model
    model = Model(network)

    # begin to infer
    image_list = get_image_list(config.INFER.image_path)
    batch_input_list = []
    img_name_list = []
    cnt = 0
    print(f'[Start infer `{config.model_name}`]')
    print("=" * 80)
    for idx, image_path in enumerate(image_list):
        image = coimg.imread(image_path, flag="grayscale")
        img = preprocess(image, config)
        batch_input_list.append(img)
        img_name = image_path.split("/")[-1]
        img_name_list.append(img_name)
        cnt += 1
        if cnt % config.INFER.batch_size == 0 or (idx + 1) == len(image_list):
            batch_input_list = np.expand_dims(np.array(batch_input_list), axis=1)
            batch_input_list = Tensor(batch_input_list, mindspore.float32)
            batch_outputs = model.predict(batch_input_list)
            print(batch_outputs)
            batch_input_list = []
            img_name_list = []
    print(f'[End of infer `{config.model_name}`]')


if __name__ == '__main__':
    args = parse_args()
    main(args)
